package com.example.miaosha.controller;

import com.example.miaosha.constant.Constant;
import com.example.miaosha.entity.MiaoShaGoods;
import com.example.miaosha.entity.R;
import com.example.miaosha.service.IMiaoShaGoodsService;
import com.example.miaosha.util.RedisUtil;
import com.example.miaosha.vo.MiaoShaGoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 秒杀商品控制器
 * @author kangnan
 * @date 2021/5/21 1:00
 **/
@RestController
@RequestMapping("/miaoShaGoods")
public class MiaoShaGoodsController {

    @Autowired
    private IMiaoShaGoodsService miaoShaGoodsService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 查询所有秒杀商品
     * @return
     */
    @RequestMapping("/findAll")
    public R findAll() {
        List<MiaoShaGoodsVo> miaoShaGoodsList = null;
        Object object = redisUtil.get(Constant.REDIS_MIAOSHA_GOODS);
        if (object == null) {
            System.out.println("select from db.");
            miaoShaGoodsList = miaoShaGoodsService.listAll();
            redisUtil.set(Constant.REDIS_MIAOSHA_GOODS, miaoShaGoodsList, Constant.REDIS_MIAOSHA_GOODS_EXPIRE);
        } else {
            System.out.println("select from redis.");
            miaoShaGoodsList = (List<MiaoShaGoodsVo>) object;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("data", miaoShaGoodsList);
        return R.ok(map);
    }

    /**
     * 根据id查询秒杀商品详情
     * @param id
     * @return
     */
    @RequestMapping("/detail")
    public R detail(Integer id) {
        MiaoShaGoods miaoShaGoods = miaoShaGoodsService.findById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("data", miaoShaGoods);
        return R.ok(map);
    }

}
